package com.chuanke.ckfamily.service.common.impl;

import com.chuanke.ckfamily.dao.common.SysConfigDao;
import com.chuanke.ckfamily.dao.common.model.SysConfig;
import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.SysConfigService;
import com.weijie.core.BaseBiz;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysConfigServiceImpl extends BaseBiz<SysConfig, SysConfigDao> implements SysConfigService {
	@Autowired
	private CacheService<String, Object> cacheService;
	private static final String PREFIX = CacheService.KEY_PREFIX.config_.toString();
	private static final Logger logger =LoggerFactory.getLogger(SysConfigServiceImpl.class);

	public void addAllCache() {
		List<SysConfig> list = findAll();
		logger.debug("初始化系统配置项:");
		for(SysConfig cfg : list) {
			cacheService.set(PREFIX + cfg.getK(), cfg);
		}
	}

	public SysConfig getCfg(String key) {
		SysConfig cfg =  (SysConfig) cacheService.get(PREFIX + key);
		if(cfg == null) {
			addAllCache();
			cfg = (SysConfig) cacheService.get(PREFIX + key);
		}
		return cfg;
	}

	public String getValue(String key) {
		SysConfig cfg = getCfg(key);
		return cfg == null ? "" : cfg.getV();
	}

	public int getIntegerValue(String key, Integer defaultValue) {
		String cvalue = getValue(key);
		if (StringUtils.isEmpty(cvalue)) {
			if (defaultValue != null) {
				return defaultValue;

			} else {
				return Integer.MIN_VALUE;

			}

		}

		return Integer.parseInt(cvalue);
	}

	public long getLongValue(String key, Long defaultValue) {
		String cvalue = getValue(key);
		if (StringUtils.isEmpty(cvalue)) {
			if (defaultValue != null) {
				return defaultValue;

			} else {
				return Long.MIN_VALUE;

			}

		} else {
			return Long.parseLong(cvalue);

		}
	}

	@Override
	public SysConfig findByName(String name) {
		return baseDao.findByName(name);
	}

	@Override
	public List<String> findIpByName() {
		List<String> ips = (List<String>) cacheService.get(CacheService.KEY_PREFIX.ckeck_ip.name());
		if(ips == null || ips.isEmpty()){
			ips = baseDao.findIpByName();
			cacheService.set(CacheService.KEY_PREFIX.ckeck_ip.name(),ips);
		}
		return ips;
	}
}